import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import 'NoteItem.dart';

class NoteListItemWidget extends StatefulWidget {
  NoteListItemWidget({
    super.key,
    required this.noteItem,
  });

  final NoteItem noteItem;

  @override
  _NoteListItemWidgetState createState() => _NoteListItemWidgetState();
}

class _NoteListItemWidgetState extends State<NoteListItemWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 5.0, horizontal: 0.0),
      padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 15.0),
      //边框设置
      decoration: new BoxDecoration(
        //背景
        color: Color(0xFFFFFFFF),
        //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.0), topRight: Radius.circular(10.0)),
        //设置四周边框
        border: new Border.all(width: 1, color: Color(0xFFf1f1f1)),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          NoteListAuthorBar(
              username: widget.noteItem.username,
              avatarUrl: widget.noteItem.avatarUrl,
              showTime: widget.noteItem.time),
          Text(
            widget.noteItem.textContent ?? "",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.normal,
              color: Color(0xFF666666),
            ),
          ),
          NoteListImage(
              images: (widget.noteItem.images != null
                  ? widget.noteItem.images
                  : [])),
          NoteListBottom(
              liked: widget.noteItem.liked,
              likeNum: widget.noteItem.likeNum,
              categoryName: widget.noteItem.categoryName),
        ],
      ),
    );
  }
}

// 顶部header
class NoteListAuthorBar extends StatelessWidget {
  const NoteListAuthorBar({
    super.key,
    this.username,
    this.avatarUrl,
    this.showTime,
  });

  final String? username;
  final String? avatarUrl;
  final String? showTime;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(bottom: 10),
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          CircleAvatar(
            backgroundImage: NetworkImage(avatarUrl ?? ""),
          ),
          Padding(
            padding: EdgeInsets.only(left: 10),
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                username ?? "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF444444),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 5),
              ),
              Text(
                showTime ?? "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.normal,
                  color: Color(0xFF444444),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

// 显示图片
class NoteListImage extends StatelessWidget {
  const NoteListImage({
    super.key,
    this.images,
  });

  final List<NoteImage>? images;

  Widget layoutOfImages(List images, BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double containW = screenWidth - 30;
    if (images.length == 1) {
      NoteImage noteImage = images[0];
      double imgWidth = 0;
      double imgHeight = 0;
      if (noteImage.imageWidth != null &&
          noteImage.imageWidth!.isNotEmpty &&
          noteImage.imageHeight != null &&
          noteImage.imageHeight!.isNotEmpty) {
        imgWidth = double.parse(noteImage.imageWidth!);
        imgHeight = double.parse(noteImage.imageHeight!);
        if (imgWidth > 0 && imgHeight > 0) {
          if (imgWidth < 1.0 && imgHeight < 1.0) {
            double maxLen = containW / 2.0;
            double showW = maxLen;
            double showH = maxLen;
            return Container(
              height: showH,
              width: showW,
              child: CachedNetworkImage(
                imageUrl: noteImage.imageUrl ?? "",
                placeholder: (context, url) =>
                    const Center(child: CupertinoActivityIndicator()),
                errorWidget: (context, url, error) => const Icon(Icons.error),
                fit: BoxFit.cover,
              ),
            );
          } else {
            double imageScale = imgWidth / imgHeight;
            double len1_3 = (containW - 20) / 3.0;
            double maxLen = len1_3 * 2 + 10;
            double showW = 0;
            double showH = 0;

            if (imageScale > 1.0) {
              // 横图
              showW = maxLen;
              showH = showW / imageScale;
            } else {
              // 竖图
              showH = maxLen;
              showW = imageScale * showH;
            }

            return Container(
              height: showH,
              width: showW,
              child: CachedNetworkImage(
                imageUrl: noteImage.imageUrl ?? "",
                placeholder: (context, url) =>
                    Center(child: CupertinoActivityIndicator()),
                errorWidget: (context, url, error) => Icon(Icons.error),
                fit: BoxFit.cover,
              ),
            );
          }
        }
      }
    } else if (images.length >= 2) {
      double showImageW = 0;
      if (images.length == 2 || images.length == 4) {
        showImageW = (containW - 10) / 2.0;
      } else {
        showImageW = (containW - 20) / 3.0;
      }
      List<Widget> imageWidgets = [];

      for (int index = 0; index < images.length; index++) {
        NoteImage noteImage = images[index];
        Widget widget = Container(
            height: showImageW,
            width: showImageW,
            child: CachedNetworkImage(
              imageUrl: noteImage.imageUrl ?? "",
              placeholder: (context, url) =>
                  Center(child: CupertinoActivityIndicator()),
              errorWidget: (context, url, error) => Icon(Icons.error),
              fit: BoxFit.cover,
            ));
        imageWidgets.add(widget);
      }

      return Container(
        alignment: Alignment.center,
        width: containW,
        child: Wrap(
          spacing: 8.0,
          // 主轴(水平)方向间距
          runSpacing: 8.0,
          // 纵轴（垂直）方向间距
          alignment: WrapAlignment.start,
          //沿主轴方向居中
          crossAxisAlignment: WrapCrossAlignment.center,
          children: imageWidgets,
        ),
      );
    }

    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 0),
      child: layoutOfImages(this.images ?? [], context),
    );
  }
}

// 显示底部
class NoteListBottom extends StatelessWidget {
  const NoteListBottom({
    super.key,
    this.liked,
    this.likeNum,
    this.categoryName,
  });

  final bool? liked;
  final String? likeNum;
  final String? categoryName;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
            //边框设置
            decoration: new BoxDecoration(
              //背景
              color: Color(0xFFFFFFFF),
              //设置四周圆角 角度 这里的角度应该为 父Container height 的一半
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.0),
                  topRight: Radius.circular(10.0)),
              //设置四周边框
              border: new Border.all(width: 1, color: Color(0xFFf1f1f1)),
            ),
            child: Text(
              this.categoryName ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.normal,
                color: Color(0xFF444444),
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextButton(
                  onPressed: () {},
                  child: const Text('Like'),
                ),
                TextButton(
                  child: Wrap(
                    // 可以通过设置两个基础组件的间距
                    alignment: WrapAlignment.center, //沿主轴方向居中
                    crossAxisAlignment: WrapCrossAlignment.center,
                    spacing: 5,
                    children: [
                      Icon(Icons.comment, color: Color(0xFFA9A9A9)),
                      Text("评论",
                          style:
                              TextStyle(fontSize: 12, color: Color(0xFF888888)))
                    ],
                  ),
                  onPressed: () {},
                ),
                TextButton(
                  child: Wrap(
                    // 可以通过设置两个基础组件的间距
                    alignment: WrapAlignment.center, //沿主轴方向居中
                    crossAxisAlignment: WrapCrossAlignment.center,
                    spacing: 5,
                    children: [
                      Icon(Icons.share, color: Color(0xFFA9A9A9)),
                      Text("分享",
                          style:
                              TextStyle(fontSize: 12, color: Color(0xFF888888)))
                    ],
                  ),
                  onPressed: () {},
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
